<template>
  <div>
  <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="基本信息" name="first"><div>
    <el-row :gutter="undefined">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="108px"
      >
        <el-col :span="14">
          <el-form-item label="楼盘名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入楼盘名称" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="楼盘地址" prop="address">
            <template>
              <label>楼盘地址:<input v-model="formData.address" class="lineinput" style="width:200px" size="mini"></label>
              <baidu-map class="map" :center="center" :zoom="zoom" @ready="handler"
                         :scroll-wheel-zoom="true"
                         @click="clickEvent"
                         ak="Hrwa4NsDzEVZUBLtcI35rQmDIbTMCQVP">
                <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>
                <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"  :showAddressBar="true" :autoLocation="true" @locationSuccess="getLoctionSuccess" ></bm-geolocation>
                <bm-view :style="{width:'100%',height: '300px',flex: 1,marginTop:'0px'}"></bm-view>
                <bm-local-search :keyword="formData.address" :auto-viewport="false" :location="formData.address" style="height: 150px;overflow-y: scroll;margin: 2px 0"></bm-local-search>
              </baidu-map>
              <div class="demo-input-suffix" style="margin-top: 2vh">
                <el-link type="info">经度：</el-link><el-input  class="lineinput"  style="width:200px" size="mini" v-model.number="locData.longitude" :disabled="true"></el-input>
                <el-link type="info"> 纬度：</el-link><el-input  class="lineinput"  style="width:200px" size="mini" v-model.number="locData.latitude" :disabled="true"></el-input>
                <el-link type="info"> 位置：</el-link><el-input  class="lineinput"  style="width:200px" size="mini" v-model="locData.address" :disabled="true"></el-input>
              </div>
            </template>
           <!-- <el-input v-model="formData.address" placeholder="请输入楼盘地址" clearable :style="{width: '60%'}" @blur="inputBlur">
            </el-input>-->
          </el-form-item>
        </el-col>
        <!--<el-col :span="24" style="height: 200px;width: 200px">
        <div style="height: 200px;width: 200px">
          <Demo></Demo>
        </div>
        </el-col>-->
        <el-col :span="14">
          <el-form-item label="省" prop="province">
            <el-select v-model="formData.province" placeholder="请选择省" clearable :style="{width: '30%'}"
                       @change="provinceChange">
              <el-option v-for="(item, index) in provinceOptions" :key="index" :label="item.regionName"
                         :value="item.regionId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="市" prop="city">
            <el-select v-model="formData.city" placeholder="请选择市" clearable :style="{width: '30%'}"
                       @change="cityChange">
              <el-option v-for="(item, index) in cityOptions" :key="index" :label="item.regionName"
                         :value="item.regionId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="县" prop="county">
            <el-select v-model="formData.county" placeholder="请选择县" clearable :style="{width: '30%'}"
                       @change="countryChange">
              <el-option v-for="(item, index) in countyOptions" :key="index" :label="item.regionName"
                         :value="item.regionId"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="商圈" prop="commercialArea">
            <el-checkbox-group v-model="formData.commercialArea" size="medium">
              <el-checkbox v-for="(item, index) in commercialAreaOptions" :key="index" :label="item.id"
                           :disabled="item.disabled">{{ item.station }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="地铁" prop="subway">
            <el-checkbox-group v-model="formData.subway" size="medium" @change="subwayChange">
              <el-checkbox v-for="(item, index) in subwayOptions" :key="index" :label="item.id"
              >{{ item.subway }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="建筑面积" prop="proportion">
            <el-input v-model="formData.proportion" placeholder="请输入建筑面积" clearable :style="{width: '60%'}">
              <template slot="append">平方米</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="建筑类型" prop="buildingType">
            <el-checkbox-group v-model="formData.buildingType" size="medium">
              <el-checkbox v-for="(item, index) in buildingTypeOptions" :key="index" :label="item.index"
                           :disabled="item.disabled">{{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="社区类型" prop="communityType">
            <el-select v-model="formData.communityType" placeholder="请选择社区类型" clearable
                       :style="{width: '60%'}">
              <el-option v-for="(item, index) in communityTypeOptions" :key="index" :label="item.name"
                         :value="item.index" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="物业类型" prop="premisesType">
            <el-checkbox-group v-model="formData.premisesType" size="medium">
              <el-checkbox v-for="(item, index) in premisesTypeOptions" :key="index" :label="item.index"
                           :disabled="item.disabled">{{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="楼盘特色" prop="propertyId">
            <el-checkbox-group v-model="formData.propertyId" size="medium">
              <el-checkbox v-for="(item, index) in propertyIdOptions" :key="index" :label="item.id"
                           :disabled="item.disabled">{{ item.premisesProperty }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="容积率" prop="grossPlotRatio">
            <el-input v-model="formData.grossPlotRatio" placeholder="请输入容积率" clearable
                      :style="{width: '60%'}">
              <template slot="append">平方米</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="得房率" prop="efficiency">
            <el-input v-model="formData.efficiency" placeholder="请输入得房率" clearable :style="{width: '60%'}">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="绿化率" prop="greenCoverage">
            <el-input v-model="formData.greenCoverage" placeholder="请输入绿化率" clearable
                      :style="{width: '60%'}">
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="楼栋数" prop="buildingCount">
            <el-input v-model="formData.buildingCount" placeholder="请输入楼栋数" clearable
                      :style="{width: '60%'}">
              <template slot="append">栋</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="开发商 " prop="developer">
            <el-input v-model="formData.developer" placeholder="请输入开发商 " clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="物业管理公司" prop="estate">
            <el-input v-model="formData.estate" placeholder="请输入物业管理公司" clearable :style="{width: '60%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="楼盘简介" prop="introduce">
            <el-input v-model="formData.introduce" type="textarea" placeholder="请输入楼盘简介"
                      :autosize="{minRows: 4, maxRows: 4}" :style="{width: '60%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="周边配套">
            <el-button @click="HandleAddRowAssort">添加</el-button>
            <ul v-for="(assort,index) in formData.assortOptions">
              <li>
                <el-input v-model="assort.title" type="text" :style="{width: '30%'}"
                          placeholder="请输入标题"></el-input>
                <el-input v-model="assort.value" type="text" :style="{width: '30%'}"
                          placeholder="请输入内容"></el-input>
                <el-button @click="handleDeleteRowAssort(index)">删除</el-button>
              </li>
            </ul>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="交通情况">
            <el-button @click="HandleAddTrafficRow">添加</el-button>
            <ul v-for="(traffic,index) in formData.trafficOptions">
              <li>
                <el-input v-model="traffic.title" type="text" :style="{width: '30%'}"
                          placeholder="请输入标题"></el-input>
                <el-input v-model="traffic.value" type="text" :style="{width: '30%'}"
                          placeholder="请输入内容"></el-input>
                <el-button @click="handleDeleteRowTraffic(index)">删除</el-button>
              </li>
            </ul>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    </div></el-tab-pane>

    <el-tab-pane label="相册管理" name="second">
      <!--户型图-->
      <span>户型图:</span>
      <el-upload :on-success="handleAvatarSuccess" :file-list="formData.pictureUrl" action="http://localhost:7003/housemanager/upload"
                 :before-upload="field105BeforeUpload">
        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
      <el-button @click="kkyulan">文件预览</el-button>
      <br>
      <!-- 外景图-->
      <span>外景图:</span>
      <el-upload :on-success="handleAvatarSuccess1" :file-list="formData.pictureUrl1" action="http://localhost:7003/housemanager/upload"
                 :before-upload="field105BeforeUpload">
        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
      <el-button @click="kkyulan1">文件预览</el-button>
      <br>
      <!--施工图-->
      <span>施工图:</span>
      <el-upload :on-success="handleAvatarSuccess2" :file-list="formData.pictureUrl2" action="http://localhost:7003/housemanager/upload"
                 :before-upload="field105BeforeUpload">
        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
      <el-button @click="kkyulan2">文件预览</el-button>
      <br>
      <!--效果图-->
      <span>效果图:</span>
      <el-upload :on-success="handleAvatarSuccess3" :file-list="formData.pictureUrl3" action="http://localhost:7003/housemanager/upload"
                 :before-upload="field105BeforeUpload">
        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
      <el-button @click="kkyulan3">文件预览</el-button>
      <br>
      <!--首页图-->
      <span>首页图:</span>
      <el-upload :on-success="handleAvatarSuccess4" :file-list="formData.pictureUrl4" action="http://localhost:7003/housemanager/upload"
                 :before-upload="field105BeforeUpload">
        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
      </el-upload>
      <el-button @click="kkyulan4">文件预览</el-button><br>
      <el-button type="primary" @click="submitForms">提交</el-button>
    </el-tab-pane>
  </el-tabs>
  </div>
</template>
<script>
  import {
    listHousemanager,
    getHousemanager,
    delHousemanager,
    addHousemanager,
    updateHousemanager
  } from "@/api/house/housemanager";
  import {listRegion, getRegion} from "@/api/house/region";
  import {getSubway} from "@/api/house/subway";
  import {getStation} from "@/api/house/station";
  import {getPremisesType, getBuildType, getPremisesProperty, getCommunType} from "@/api/house/type";
  import {BaiduMap,BmNavigation,BmView,BmGeolocation,BmCityList,BmLocalSearch} from 'vue-baidu-map'
  import {Pagination} from "element-ui";
  /*import demo from "@/views/house/ditu/index.vue"*/
  import {Base64} from "js-base64";
  export default {
   /* //地图
    components: {
      'Demo': demo
    },*/
    props: [],
    data() {
      return {
        center: {lng: 111.752912, lat: 40.832246},
        zoom: 12,
        mapVisible:false,
        locData:{
          longitude:'',
          latitude:'',
          address:'',},
        input:'',
        formData: {
          pictureUrl: '',
          pictureUrl1:'',
          pictureUrl2:'',
          pictureUrl3:'',
          pictureUrl4:'',
          name: null,
          address: null,
          province: null,
          city: null,
          county: null,
          commercialArea: [],
          subway: [],
          proportion: null,
          buildingType: [],
          communityType: null,
          premisesType: [],
          propertyId: [],
          grossPlotRatio: null,
          efficiency: null,
          greenCoverage: null,
          buildingCount: null,
          developer: null,
          estate: null,
          introduce: null,
          trafficOptions: [
            {
              title: '',
              value: ''
            }
          ],
          assortOptions: [
            {
              title: '',
              value: ''
            }
          ]
        },
        rules: {
          name: [{
            required: true,
            message: '请输入楼盘名称',
            trigger: 'blur'
          }],
          address:'',
          province: [],
          city: [],
          county: [],
          commercialArea: [],
          subway: [],
          subways:"",
          proportion: [],
          buildingType: [],
          communityType: [],
          premisesType: [],
          propertyId: [],
          grossPlotRatio: [],
          efficiency: [],
          greenCoverage: [],
          buildingCount: [],
          developer: [],
          estate: [],
          introduce: [],
        },
        provinceOptions: [],
        cityOptions: [],
        countyOptions: [],
        commercialAreaOptions: [],
        subwayOptions: [],
        buildingTypeOptions: [],
        communityTypeOptions: [],
        premisesTypeOptions: [],
        propertyIdOptions: [],
        activeName: 'first',
      }
    },
    computed: {},
    watch: {},
    created() {
      this.getRegion();
    },
    mounted() {
    },
    methods: {
     //图片预览
      submitForms() {
        if(this.formData.pictureUrl==null || this.formData.pictureUrl==""){
          console.log("pictureUrl==null")
          return false;
        }
        if(this.formData.pictureUrl1==null || this.formData.pictureUrl1==""){
          console.log("pictureUrl1==null")
          return false;
        }
        if(this.formData.pictureUrl2==null || this.formData.pictureUrl2==""){
          console.log("pictureUrl2==null")
          return false;
        }
        if(this.formData.pictureUrl3==null || this.formData.pictureUrl3==""){
          console.log("pictureUrl3==null")
          return false;
        }
        if(this.formData.pictureUrl4==null || this.formData.pictureUrl4==""){
          console.log("pictureUrl4==null")
          return false;
        }
        // TODO 提交表单
        console.log(this.formData);
         addHousemanager(this.formData).then(response => {
         this.formData.subways =  this.formData.subway.join()
          if(response.code==200){
            this.$message.success("添加成功!!!");
            this.$router.push({path:"index"});
          }else{
             this.$message.error("添加失败!!!");
           }
         })
      },
      //图片验证规则
       field105BeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize
      },
      //图片预览
      kkyulan(){
        var url=this.formData.pictureUrl
        window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
      },
      kkyulan1(){
        var url=this.formData.pictureUrl1
        window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
      },
      kkyulan2(){
        var url=this.formData.pictureUrl2
        window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
      },
      kkyulan3(){
        var url=this.formData.pictureUrl3
        window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
      },
      kkyulan4(){
        var url=this.formData.pictureUrl4
        window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
      },
      //图片返回数据
      handleAvatarSuccess(res,file){

        this.formData.pictureUrl=res.url
      },
      handleAvatarSuccess1(res,file){

        this.formData.pictureUrl1=res.url
      },
      handleAvatarSuccess2(res,file){

        this.formData.pictureUrl2=res.url
      },
      handleAvatarSuccess3(res,file){

        this.formData.pictureUrl3=res.url
      },handleAvatarSuccess4(res,file){
        console.log(res)
        this.formData.pictureUrl4=res.url
      },

      submitForm() {
        this.$refs['elForm'].validate(valid => {
          if (!valid) return
          //TODO 提交表单
          this.activeName='second';
          // console.log(this.formData);
          // addHousemanager(this.formData).then(response => {
          //   this.formData.subways =  this.formData.subway.join()
          //   // this.$message.success("aaa");
          // /*  if(response.code==200){
          //     this.$message.success("添加成功!!!");*/
          //     this.activeName='second';
          //   /*}else{
          //     this.$message.error("添加失败!!!");
          //   }*/
          // })
        })

      },
      resetForm() {
        this.$refs['elForm'].resetFields()
      },
      getRegion() {
        listRegion(this.queryParams).then(response => {
          this.provinceOptions = this.handleTree(response.data, "regionId", "parentId");
        });

        getPremisesType().then(response => {
          this.premisesTypeOptions = response.data;
        });

        getBuildType().then(response => {
          this.buildingTypeOptions = response.data;
        });

        getPremisesProperty().then(response => {
          this.propertyIdOptions = response.data;
        });
        getCommunType().then(response => {
          this.communityTypeOptions = response.data;
        });
        console.log(this.$route.query);

      },
      provinceChange(value) {
        this.subwayOptions = [];
        this.countyOptions = [];
        this.cityOptions = [];
        this.formData.county = '';
        this.formData.city = '';
        getRegion(this.formData.province).then(response => {
          this.cityOptions = response.data;
        });
        getSubway(value).then(response => {
          this.subwayOptions = response.data;
        })
        console.log(value);
      },
      cityChange(value) {
        this.countyOptions = [];
        this.formData.county = '';
        getRegion(this.formData.city).then(response => {
          this.countyOptions = response.data;
        });
      },
      countryChange(value) {

      },
      subwayChange(value) {
        console.log(value+"====================================")
        getStation(value).then(response => {
          this.commercialAreaOptions = response.data;
        })
      },
      HandleAddRowAssort() {
        this.formData.assortOptions.push({
          title: '',
          value: ''
        })
      },
      handleDeleteRowAssort(index) {
        this.formData.assortOptions.splice(index, 1);
      },
      handleDeleteRowTraffic(index) {
        this.formData.trafficOptions.splice(index, 1);
      },
      HandleAddTrafficRow() {
        this.formData.trafficOptions.push({
          title: '',
          value: ''
        })
      },
      handler ({BMap, map}) {
        let _this = this;  // 设置一个临时变量指向vue实例，因为在百度地图回调里使用this，指向的不是vue实例；
        let geolocation = new BMap.Geolocation();
        geolocation.getCurrentPosition(function(r){
          console.log(r);
          _this.center = {lng: r.longitude, lat: r.latitude};   // 设置center属性值
          _this.autoLocationPoint = {lng: r.longitude, lat: r.latitude};  // 自定义覆盖物
          _this.initLocation = true;
        },{enableHighAccuracy: true})
        window.map = map;
      },
      //点击地图监听
      clickEvent(e){
        map.clearOverlays();
        let Icon_0 = new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 25)});
        let myMarker = new BMap.Marker(new BMap.Point(e.point.lng, e.point.lat),{icon: Icon_0});
        map.addOverlay(myMarker);
        //用所定位的经纬度查找所在地省市街道等信息
        let point = new BMap.Point(e.point.lng, e.point.lat);
        let gc = new BMap.Geocoder();
        let _this = this;
        gc.getLocation(point, function (rs) {
          let addComp = rs.addressComponents;
          _this.locData.address = rs.address;

        });
        this.locData.longitude = e.point.lng;
        this.locData.latitude = e.point.lat;
      },
//定位成功回调
      getLoctionSuccess(point, AddressComponent, marker){
        map.clearOverlays();
        let Icon_0 = new BMap.Icon("http://api0.map.bdimg.com/images/marker_red_sprite.png", new BMap.Size(64, 64), {anchor: new BMap.Size(18, 32),imageSize: new BMap.Size(36, 36)});
        let myMarker = new BMap.Marker(new BMap.Point(point.point.lng, point.point.lat),{icon: Icon_0});
        map.addOverlay(myMarker);
        this.locData.longitude = point.point.lng;
        this.locData.latitude = point.point.lat;
      },
//返回选中点的位置
      findlocation(){
        this.$emit("findlocdata",this.locData)
        this.temp.location=this.keyword
        this.temp.lng=this.locData.longitude
        this.temp.lat=this.locData.latitude
        this.mapVisible = false
      },
    },
     components: {
      Pagination,
      BaiduMap,
      BmNavigation,
      BmView,
      BmGeolocation,
      BmCityList,
      BmLocalSearch
     },
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
